<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Admin extends CI_Controller
{
    const IMAGE_UPLOAD_DIR = 'resources/upload/images';
    const IMAGE_THUMB_UPLOAD_DIR = 'resources/upload/images/thumb';
	function __construct()
	{
		parent::__construct();
        $this->load->library('Datatables');
        $this->load->library('table');
		$this->load->helper(array('form','url'));
		$this->load->library(array('tank_auth','form_validation'));
        $this->_supported_extensions = array('jpg', 'jpeg', 'gif', 'png', 'pdf');
		$this->load->model('posts');
        $this->load->model('project');
        $this->load->model('tags');

	}

	function index() {
		if (!$this->tank_auth->is_logged_in()) {
			redirect('/auth/login');
		} else {
			$data['userId'] = $this->tank_auth->get_user_id();
			$data['username'] = $this->tank_auth->get_username();
	
			$this->load->view('template/admin_head', $data);
            $this->load->view('template/admin_script');
			$this->load->view('admin/index', $data);
			$this->load->view('template/admin_footer', $data);
		}
	}

    function ajax_datatable()
    {
        //$columns = array('id','title','summary','content','created');
        //$table = 'posts';
        $this->datatables->select('id,title,summary,content,created')->from('posts');
        echo $this->datatables->generate();
    }

	function create(){
		$data['userId'] = $this->tank_auth->get_user_id();
		$data['username'] = $this->tank_auth->get_username();
        //$data['post_tag'] =
		$this->form_validation->set_rules('title','title','required');
		$this->form_validation->set_rules('summary','summary','required');
		$this->form_validation->set_rules('content','content','required');

		if($this->form_validation->run()==FALSE)
		{
			$this->load->view('template/admin_head',$data);
            $this->load->view('template/admin_script');
			//$this->load->view('admin/create_post',$data);
            $this->load->view('admin/create_post',
                array(
                    'ckeditor' => $this->_setup_ckeditor('content'),
                    'content_html' => '', // your model property's HTML for CKEditor textarea
                    'post_tag' => $this->tags->get_post_tag(null)
                ));
            $this->load->view('template/admin_footer');

		} else {
			$data = $_POST;
            if($_FILES['file']['size']>0)
            {
                $data['img_url'] = $this->_move_image($_FILES['file']);
            }
			$this->posts->insert_post($data);
			redirect('admin');
		}
	}

    function project_new(){
        $data['userId'] = $this->tank_auth->get_user_id();
        $data['username'] = $this->tank_auth->get_username();
        //$data['post_tag'] =
        $this->form_validation->set_rules('title','title','required');
        $this->form_validation->set_rules('summary','summary','required');
        $this->form_validation->set_rules('content','content','required');

        if($this->form_validation->run()==FALSE)
        {
            $this->load->view('template/admin_head',$data);
            $this->load->view('template/admin_script');
            //$this->load->view('admin/create_post',$data);
            $this->load->view('admin/project_new',
                array(
                    'ckeditor' => $this->_setup_ckeditor('content'),
                    'content_html' => '', // your model property's HTML for CKEditor textarea
                    'post_tag' => $this->tags->get_post_tag(null)
                ));
            $this->load->view('template/admin_footer');

        } else {
            $data = $_POST;
            if($_FILES['file']['size']>0)
            {
                $image_upload = $this->_upload_image($_FILES['file']);
                $data['img_url'] = $image_upload['file_path'];
                $data['img_thumb_url'] = $image_upload['file_thumb_path'];
            }
            $this->project->insert_project($data);
            redirect('admin');
        }
    }

	function edit($postId){
		$data['userId'] = $this->tank_auth->get_user_id();
		$data['username'] = $this->tank_auth->get_username();
		$data['post'] = $this->posts->get_posts($postId);
        $data['ckeditor'] = $this->_setup_ckeditor('content');
        $data['post_tag'] = $this->tags->get_post_tag(null);

		$this->form_validation->set_rules('title','title','required');
		$this->form_validation->set_rules('summary','summary','required');
		$this->form_validation->set_rules('content','content','required');

		if($this->form_validation->run()==FALSE)
		{
            $this->load->view('template/admin_head',$data);
            $this->load->view('template/admin_script');
			$this->load->view('admin/edit',$data);
            $this->load->view('template/admin_footer');
		} else {
			$data = $_POST;
			$this->posts->update_post($postId,$data);
			redirect('admin');
		}
	}

	function delete($postId){
        $postId = $_POST['id'];
		$this->posts->delete_post($postId);
		redirect('admin');
	}

	function logout(){
		redirect ('/auth/logout');
	}

    /**
     * Output CKEditor Javascript callback function for image file uploaded
     * in $_FILES['upload']. The GET parameters must also contain the
     * CKEditorFuncNum parameter so the JavaScript callback will reference
     * the correct CKEditor instance.
     */
    public function upload()
    {
        $callback = 'null';
        $url = '';
        $get = array();

        // for form action, pull CKEditorFuncNum from GET string. e.g., 4 from
        // /form/upload?CKEditor=content&CKEditorFuncNum=4&langCode=en
        // Convert GET parameters to PHP variables
        $qry = $_SERVER['REQUEST_URI'];
        parse_str(substr($qry, strpos($qry, '?') + 1), $get);

        if (!isset($_POST) || !isset($get['CKEditorFuncNum'])) {
            $msg = 'CKEditor instance not defined. Cannot upload image.';
        } else {
            $callback = $get['CKEditorFuncNum'];

            try {
                $url = $this->_move_image($_FILES['upload']);
                $msg = "File uploaded successfully to: {$url}";

                // Persist additions to file manager CMS here.

            } catch (Exception $e) {
                $url = '';
                $msg = $e->getMessage();
            }
        }

        $output = '<html><body><script type="text/javascript">' .
            'window.parent.CKEDITOR.tools.callFunction(' .
            $callback .
            ', "' .
            $url .
            '", "' .
            $msg .
            '");</script></body></html>';

        echo $output;
    }

    /**
     * Move uploaded file to the storage directory only if its MIME type is
     * accepted.
     *
     * @param $temp_location $_FILES array entry w/ details of local file.
     * @throws Exception When there are issues moving file to upload directory.
     */
    private function _move_image($temp_location)
    {
        $filename = time().basename($temp_location['name']);
        $info = pathinfo($filename);
        $ext = strtolower($info['extension']);
        if (isset($temp_location['tmp_name']) &&
            isset($info['extension']) &&
            in_array($ext, $this->_supported_extensions)) {
            $new_file_path = self::IMAGE_UPLOAD_DIR . "/$filename";
            if (!is_dir(self::IMAGE_UPLOAD_DIR) ||
                !is_writable(self::IMAGE_UPLOAD_DIR)) {
                // Attempt to auto-create upload directory.
                if (!is_writable(self::IMAGE_UPLOAD_DIR) ||
                    FALSE === @mkdir(self::IMAGE_UPLOAD_DIR, null , TRUE)) {
                    throw new Exception('Error: File permission issue, ' .
                        'please consult your system administrator');
                }
            }

            if (move_uploaded_file($temp_location['tmp_name'], $new_file_path)) {
                $this->watermark_image($new_file_path);
                return "/".$new_file_path;
            }
        }

        throw new Exception('File could not be uploaded.');
    }

    /**
     * Move uploaded file to the storage directory only if its MIME type is
     * accepted.
     *
     * @param $temp_location $_FILES array entry w/ details of local file.
     * @throws Exception When there are issues moving file to upload directory.
     */
    private function _upload_image($temp_location)
    {
        $filename = time().basename($temp_location['name']);
        $info = pathinfo($filename);
        $ext = strtolower($info['extension']);
        if (isset($temp_location['tmp_name']) &&
            isset($info['extension']) &&
            in_array($ext, $this->_supported_extensions)) {
            $new_file_path = self::IMAGE_UPLOAD_DIR . "/$filename";
            $new_thumb_file_path = self::IMAGE_THUMB_UPLOAD_DIR . "/$filename";
            if (!is_dir(self::IMAGE_UPLOAD_DIR) ||
                !is_writable(self::IMAGE_UPLOAD_DIR)) {
                // Attempt to auto-create upload directory.
                if (!is_writable(self::IMAGE_UPLOAD_DIR) ||
                    FALSE === @mkdir(self::IMAGE_UPLOAD_DIR, null , TRUE)) {
                    throw new Exception('Error: File permission issue, ' .
                        'please consult your system administrator');
                }
            }

            if (move_uploaded_file($temp_location['tmp_name'], $new_file_path)) {
                $this->watermark_image($new_file_path);
                $file_thumb_path = $this->resize_image($new_file_path , $new_thumb_file_path,290,177);
                return array(
                    'file_path' => "/".$new_file_path,
                    'file_thumb_path' => "/".$file_thumb_path, // your model property's HTML for CKEditor textarea
                );
            }
        }

        throw new Exception('File could not be uploaded.');
    }

    /**
     * Retrieve configuration properties for CKEditor instance. Ensure the
     * CodeIgniter helper has been copied to CI's system directory.
     *
     * @param $id HTML id="" attribute CKEditor instance is enabled for.
     *
     * @return array First parameter for display_ckeditor() function invoked
     *         in the CI view.
     */
    private function _setup_ckeditor($id)
    {
        $this->load->helper('url');
        $this->load->helper('ckeditor');

        $ckeditor = array(
            'id' => $id,
            'path' => 'resources/ckeditor',
            'config' => array(
                'toolbar' => 'Full',
                'width' => 'auto',
                'height' => '400px',
                'filebrowserImageUploadUrl' => base_url().'index.php/admin/upload'));

        return $ckeditor;
    }


    public function resize_image($file_path,$thumb_file_path, $width, $height) {
        $this->load->library('image_lib');
        $img_cfg['image_library'] = 'gd2';
        $img_cfg['source_image'] = $file_path;
        $img_cfg['maintain_ratio'] = TRUE;
        $config['create_thumb'] = TRUE;
        $img_cfg['new_image'] = $thumb_file_path;
        $img_cfg['width'] = $width;
        $img_cfg['quality'] = 100;
        $img_cfg['height'] = $height;
        $this->image_lib->initialize($img_cfg);
        $this->image_lib->resize();
        $this->image_lib->clear();
        return $thumb_file_path;
    }

    public function watermark_image($file_path) {
        $this->load->library('image_lib');
       // $config['image_library'] = 'gd2';
       // $config['source_image'] = $file_path;
        //$config['wm_overlay_path'] = './system/fonts/watermark.png';
      $config['image_library']  = 'ImageMagick';
      $config['library_path'] = '/usr/local/bin/';
      $config['source_image'] = $file_path;
      //$config['create_thumb']  = TRUE;
      $config['maintain_ratio'] = TRUE;
      //$config['width']      = 150;

      $config['wm_type'] = 'overlay';
      $config['wm_overlay_path'] = './system/fonts/watermark.png';
      $config['wm_vrt_alignment'] = 'bottom';
      $config['wm_hor_alignment'] = 'right';

        $this->image_lib->initialize($config);
        $this->image_lib->watermark();
        $this->image_lib->clear();
    }

}
